package cn.net.xyan.yypt.controller

import cn.net.xyan.blossom.kotlin.javaType
import cn.net.xyan.blossom.kotlin.json
import cn.net.xyan.blossom.kotlin.logger
import cn.net.xyan.yypt.dto.CallbackBizContentRsp
import cn.net.xyan.yypt.service.LinkingCloudOpenApi
import cn.net.xyan.yypt.service.PayOrderService
import cn.net.xyan.yypt.service.PayOrderServiceImpl
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Controller
@RequestMapping("/public/callback")
class CallbackController{

    companion object {
        const val Success = "success"

    }

    @Autowired
    lateinit var linkingCloudOpenApi: LinkingCloudOpenApi

    @Autowired
    lateinit var payOrderService: PayOrderService

    @RequestMapping("/linkingCloud")
    @ResponseBody
    fun linkingCloud(request: HttpServletRequest, response: HttpServletResponse){

        val mapper = ObjectMapper()

        val map = HashMap<String, String>()
        request.parameterMap.forEach { t, u ->
            if (u!=null && u.isNotEmpty())
                map.put(t,u[0])
        }


        logger.info(map.json)
        val biz = map["biz_content"]

        if (biz != null && biz.isNotEmpty()){
            val bizContentRsp: CallbackBizContentRsp?
                    = mapper.readValue(biz,CallbackBizContentRsp::class.javaType)

            val service = payOrderService
            if (bizContentRsp!= null && service is PayOrderServiceImpl) {
                service.onPay(bizContentRsp)
            }
            logger.info(bizContentRsp?.json)
        }

        response.outputStream.write(Success.toByteArray(Charsets.ISO_8859_1))
    }
}